import { defineStore } from "pinia";

import { getDictInfo } from "@/api/dict";
import { store } from "@/store";

import { useStorage } from "@vueuse/core";

export const useDictStore = defineStore("dictionary", () => {
  const dictionary: any = {}; // dictionary 字典字段

  const token = useStorage("loginStorage", "", localStorage);

  /**
   * 获取全部字典信息
   *
   */
  function getDictionaryList() {
    return new Promise<OptionType[]>((resolve, reject) => {
      getDictInfo()
        .then(({ data }) => {
          Object.assign(dictionary, { ...dictionary, ...data });
          resolve(data);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 获取对应字典label
   *
   * @param {LoginData}
   * @returns
   */
  function filterDictName(code: string, value: any) {
    const filter = dictionary[code];
    return (
      filter?.find((e: any) => e.value === value?.toString())?.label ||
      value ||
      ""
    );
  }

  /**
   * 获取对应字典List
   *
   * @param {LoginData}
   * @returns
   */
  function filterDictList(code: string) {
    return dictionary[code] || [];
  }

  return {
    token,
    dictionary,
    filterDictName,
    filterDictList,
    getDictionaryList,
  };
});

// 非setup
export function useDictStoreHook() {
  return useDictStore(store);
}
